package cameragps;

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.BitmapField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.PopupScreen;

/**
 * This class contain methods to handle background tasks.
 */
public class ThreadUtils {

	/**
	 * This method runs the runnable passed as parameter and in that time it
	 * blocks user interface with a dialog
	 * 
	 * @param runThis
	 *            The runnable which contains the procedure to do.
	 */
	public static void showScreenAndWait(final Runnable runThis,final String message) {
		
		final PopupScreen waitScreen = getWaitPopUp(message);

		Thread threadToRun = new Thread() {
			public void run() {

				runningSequance(new Runnable() {
					public void run() {
						
						UiApplication.getUiApplication().pushModalScreen(waitScreen);
					}
				},

				runThis,

				new Runnable() {
					public void run() {
						UiApplication.getUiApplication().popScreen(waitScreen);
					}
				});
			}
		};
		threadToRun.start();
	}

	/**
	 * This method is used to run background tasks while allowing to reflact
	 * User interface before starting the task and after ending the task
	 * 
	 * @param runThisBefore
	 *            runnable to run before
	 * @param runThis
	 *            runnable to run the key task
	 * @param runThisAfter
	 *            runnable to run after
	 */
	public static void runningSequance(final Runnable runThisBefore,
			final Runnable runThis, final Runnable runThisAfter) {
		new Thread() {
			public void run() {
				UiApplication.getUiApplication().invokeLater(runThisBefore);
				runThis.run();
				UiApplication.getUiApplication().invokeLater(runThisAfter);

			}
		}.start();

	}
	
	public static PopupScreen getWaitPopUp(String message){
		HorizontalFieldManager popupLayout = new HorizontalFieldManager();

		popupLayout.add(new BitmapField(Bitmap
				.getPredefinedBitmap(Bitmap.HOURGLASS), Field.FIELD_VCENTER));
		 popupLayout.add(new LabelField(message, Field.FIELD_VCENTER));

		return new PopupScreen(popupLayout);
	}
}

